package com.lxf.cn.config;

import com.lxf.cn.uitl.Code;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by liaoxuefeng on 2018/11/28.
 */
@ControllerAdvice
public class BaseController {


    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {

    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     *
     *
     */
    @ExceptionHandler(value = Exception.class)
    public @ResponseBody Object errorHandler(Exception ex) {
        Map<String , Object> map = new HashMap<String ,Object>();
        map.put("exceptionCode", Code.FAIL.code);
        map.put("exceptionMsg","系统错误");

        map.put("bizContent",ex.getMessage());
        return map;
    }


    @ExceptionHandler({IllegalStateException.class})
    public @ResponseBody Object illegalStateExceptionHandLer(IllegalStateException e) {
        Map<String , Object> map = new HashMap<String ,Object>();
        map.put("exceptionCode", Code.FAIL.code);
        map.put("exceptionMsg", "系统错误");
        map.put("bizContent",e.getLocalizedMessage());
        return map;
    }


}
